#include "CEventSystem.h"

CDispatcher *CDispatcher::GetInstance()
{
	static CDispatcher instance;
	return &instance;
}

void CDispatcher::DispatchEvent(tEvent *Event)
{
	pair<multimap<string, IListener *>::iterator, multimap<string, IListener *>::iterator> iRange;

	iRange = m_mRegistry.equal_range(Event->m_szEventID);

	for (multimap<string, IListener *>::iterator iIter = iRange.first; iIter != iRange.second; iIter++)
	{
		(*iIter).second->HandleEvent(Event->m_szEventID, Event->m_pSender, Event->m_pArgs);
	}
}

void CDispatcher::RegisterClient(string szID, IListener *pClient)
{
	m_mRegistry.insert(make_pair(szID, pClient));
}

void CDispatcher::UnregisterClient(string szID, IListener *pClient)
{
	pair<multimap<string, IListener *>::iterator, multimap<string, IListener *>::iterator> iRange;

	iRange = m_mRegistry.equal_range(szID);

	for (multimap<string, IListener *>::iterator iIter = iRange.first; iIter != iRange.second; iIter++)
	{
		if ((*iIter).second == pClient)
		{
			m_mRegistry.erase(iIter);
			break;
		}
	}
}

void CDispatcher::SendEvent(string szID, void *pSender, void *pArgs)
{
	tEvent Event;
	Event.SetParams(szID, pSender, pArgs);
	m_qEvents.push(Event);
}

void CDispatcher::ProcessEvents()
{
	while (!m_qEvents.empty())
	{
		DispatchEvent(&m_qEvents.front());
		m_qEvents.pop();
	}
}

void CDispatcher::ClearEvents()
{
	while (!m_qEvents.empty())
		m_qEvents.pop();
}